package aimis.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class MapBuilder {
    public MapBuilder()
    {

    }
    public static MapBuilder fromBindingResult(BindingResult bindingResult)
    {
        var builder=new MapBuilder();
        builder.data=bindingResult.getAllErrors().stream().collect(Collectors.toMap(ObjectError::getObjectName,ObjectError::getDefaultMessage));
        return builder;
    }
    public static MapBuilder fromString(String json)
    {
        var builder=new MapBuilder();
        var mapper=new ObjectMapper();
        var data=new HashMap<String,Object>();
        try {
            data=mapper.readValue(json, HashMap.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        builder.data=data;
        return builder;
    }
    private Map<String,Object> data;
    public MapBuilder put(String key, Object value)
    {
        data.put(key,value);
        return this;
    }
    public Map<String,Object> build()
    {
        return data;
    }
}
